package com.example.coffeeseller_2.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.util.AttributeSet;
import android.widget.TextView;

/**
 * Created by hfs on 2017/5/9.
 */

@SuppressLint("AppCompatCustomView")
public class CountDownText extends TextView {

    private TimeCount mTimeCount;
    //倒计时总数
    private long millisInFuture = 10000;
    //倒计时间隔（秒）
    private long countDownInterval = 1000;

    private IntervalListener intervalListener;

    public CountDownText(Context context) {
        this(context,null);
    }

    public CountDownText(Context context, AttributeSet attrs) {
        this(context,attrs,0);
    }

    public CountDownText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {
        setTextColor(Color.WHITE);
        setTextSize(18);
    }

    /**
     * 设置倒计时多少毫秒结束
     * 默认60秒
     *
     * @param millisInFuture 毫秒
     */
    public void setMillisInFuture(long millisInFuture) {
        this.millisInFuture = millisInFuture;
    }

    public long getMillisInFuture() {
        return millisInFuture;
    }

    /**
     * 设置倒计时间隔
     * 默认1秒
     *
     * @param countDownInterval 倒计时间隔
     */
    public void setCountDownInterval(long countDownInterval) {
        this.countDownInterval = countDownInterval;
    }

    public void startCount() {
        mTimeCount = new TimeCount(millisInFuture, countDownInterval);
        mTimeCount.start();
    }
    public void stopCount() {
        if(mTimeCount != null){
            mTimeCount.cancel();
        }
    }

    private class TimeCount extends CountDownTimer {
        /**
         * @param millisInFuture    倒计时总时长
         * @param countDownInterval 倒计时单位 毫秒.
         */
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }


        @Override
        public void onTick(long millisUntilFinished) {
            if(intervalListener != null){
                intervalListener.onTick(millisUntilFinished / 1000);
            }
        }

        @Override
        public void onFinish() {
            if(intervalListener != null){
                intervalListener.onFinish();
            }
        }
    }
    public interface IntervalListener{
        void onTick(long millisUntilFinished);
        void onFinish();
    }
    public void setOnIntervalListener(IntervalListener listener){
        intervalListener = listener;
    }

}
